#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户会话管理模块
"""
import secrets
from datetime import datetime, timedelta
from fastapi import Request, HTTPException
from ..database import get_db_connection


def get_current_user(request: Request):
    """获取当前登录用户"""
    session_token = request.cookies.get("session_token")
    if not session_token:
        return None
    
    conn = get_db_connection()
    user = conn.execute("""
        SELECT u.* FROM users u
        JOIN user_sessions s ON u.id = s.user_id
        WHERE s.session_token = ? AND s.expires_at > datetime('now') AND u.is_active = 1
    """, (session_token,)).fetchone()
    conn.close()
    
    return user


def verify_user(request: Request):
    """验证用户登录"""
    user = get_current_user(request)
    if not user:
        raise HTTPException(status_code=401, detail="请先登录")
    return user


def verify_admin(request: Request):
    """验证管理员权限"""
    user = get_current_user(request)
    if not user:
        raise HTTPException(status_code=401, detail="请先登录")
    if user['role'] != 'admin':
        raise HTTPException(status_code=403, detail="权限不足")
    return user


def create_session(user_id: int) -> str:
    """创建用户会话"""
    session_token = secrets.token_urlsafe(32)
    expires_at = datetime.now() + timedelta(days=7)
    
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO user_sessions (user_id, session_token, expires_at)
        VALUES (?, ?, ?)
    """, (user_id, session_token, expires_at))
    conn.commit()
    conn.close()
    
    return session_token


def delete_session(session_token: str):
    """删除用户会话"""
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("DELETE FROM user_sessions WHERE session_token = ?", (session_token,))
    conn.commit()
    conn.close()